package gredis

import (
	"fmt"
	"runtime"
)

// A config of go redis
type Config struct {
	Network              string `yaml:"network"`
	Addr                 string `yaml:"addr"`
	Passwd               string `yaml:"password"`
	DB                   int    `yaml:"database"`
	DialTimeout          int    `yaml:"dial_timeout"`
	ReadTimeout          int    `yaml:"read_timeout"`
	WriteTimeout         int    `yaml:"write_timeout"`
	PoolSize             int    `yaml:"pool_size"`
	PoolTimeout          int    `yaml:"pool_timeout"`
	MinIdleConns         int    `yaml:"min_idle_conns"`
	MaxRetries           int    `yaml:"max_retries"`
	TraceIncludeNotFound bool   `yaml:"trace_include_not_found"`
}

// Name returns client name of the config
func (c *Config) Name() string {
	return fmt.Sprintf("%s(%s/%d)", c.Network, c.Addr, c.DB)
}

// FillWithDefaults apply default values for fields with invalid values.
func (c *Config) FillWithDefaults() {
	maxCPU := runtime.NumCPU()

	if c.DialTimeout <= 0 || c.DialTimeout > MaxDialTimeout*maxCPU {
		c.DialTimeout = MaxDialTimeout
	}

	if c.ReadTimeout <= 0 || c.ReadTimeout > MaxReadTimeout*maxCPU {
		c.ReadTimeout = MaxReadTimeout
	}

	if c.WriteTimeout <= 0 || c.WriteTimeout > MaxWriteTimeout*maxCPU {
		c.WriteTimeout = MaxWriteTimeout
	}

	if c.PoolSize <= 0 {
		c.PoolSize = 10 * maxCPU
	}

	if c.PoolTimeout <= 0 || c.PoolTimeout > MaxPoolTimeout*maxCPU {
		c.PoolTimeout = MaxPoolTimeout
	}

	if c.MinIdleConns <= 0 || c.MinIdleConns > MinIdleConns*maxCPU {
		c.MinIdleConns = MinIdleConns
	}

	if c.MaxRetries < 0 || c.MaxRetries > MaxRetries*maxCPU {
		c.MaxRetries = MaxRetries
	}
}

// A ManagerConfig defines a list of redis config with its name
type ManagerConfig map[string]*Config
